package cn.lu.joke.ui.dialog;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.lu.joke.BuildConfig;
import cn.lu.joke.R;
import cn.lu.joke.api.API;
import cn.lu.joke.base.BaseDialogFragment;
import cn.lu.joke.downloader.DownloadTask;
import cn.lu.joke.downloader.Downloader;
import cn.lu.joke.downloader.SimpleTarget;
import cn.lu.joke.entry.AppUpdate;
import cn.lu.joke.util.LogUtils;
import cn.lu.joke.util.Toast;

public class UpgradeDialog extends BaseDialogFragment {

    @BindView(R.id.tv_update_tip)
    TextView mTvUpdateTip;
    @BindView(R.id.tv_update_info)
    TextView mTvUpdateInfo;
    @BindView(R.id.tv_upgrade_cancel)
    TextView mCancel;
    @BindView(R.id.tv_upgrade_ok)
    TextView mConfirm;
    @BindView(R.id.progress_bar)
    NumberProgressBar mProgressBar;

    private AppUpdate appInfo;

    //updateType（0:建议 1:强制）:

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_upgrade;
    }

    @Override
    protected void setAttributes(WindowManager.LayoutParams params) {
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        super.setAttributes(params);
    }

    @Override
    public void initData() {
        mProgressBar.setVisibility(View.GONE);
        mTvUpdateTip.setText(appInfo.updateTip);
        mTvUpdateInfo.setText(appInfo.updateInfo);
    }

    @OnClick({R.id.tv_upgrade_cancel, R.id.tv_upgrade_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_upgrade_cancel:
                dismiss();
                break;
            case R.id.tv_upgrade_ok:
                Downloader.gen()
                        .build()
                        .create(API.baseUrl_noRod + appInfo.url)
                        .setPath(getActivity().getExternalCacheDir().getAbsolutePath() + "/update.apk")
                        .setDownloadListener(new SimpleTarget() {

                            @Override
                            public void onStart(DownloadTask task) {
                                mProgressBar.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onProgress(long length, long progress) {
                                mProgressBar.setProgress((int) ((progress * 1.0 / length) * 100));
                            }

                            @Override
                            public void onComplete(String path) {
                                install(path);
                            }

                            @Override
                            public void onFailure(Exception e) {
                                Toast.showErr(e.getMessage());
                                e.printStackTrace();
                            }
                        })
                        .start();
                break;
        }
    }

    private void install(String filePath) {
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //Log.w(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    getActivity(),
                    String.format("%s.fileProvider", BuildConfig.APPLICATION_ID),
                    apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    public void setAppInfo(AppUpdate appInfo) {
        this.appInfo = appInfo;
    }
}
